package com.acooly.module.openapi.client.provider.allinpay.utils;

import com.acooly.core.common.exception.BusinessException;
import com.acooly.core.utils.Encodes;

import javax.servlet.ServletRequest;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;

public class StringHelper {

    /**
     * 将map中的值转化为字符，并以|分开
     *
     * @param params
     * @return
     */
    public static String mapToStr(Map<String, Object> params) {
        StringBuffer returnStr = new StringBuffer();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            returnStr.append(entry.getValue() + "|");
        }
        return returnStr.substring(0, returnStr.length() - 1);
    }

    /**
     * 返回参数处理
     * @return
     * @throws Exception
     */
    public static Map<String,String> getResponseParm(String Rstr) {
        Map<String,String> DateArry = new TreeMap<String,String>();
        String[] ListObj=Rstr.split("&");
        for(String Temp:ListObj){
            if(Temp.matches("(.+?)=(.+?)")){
                String[] TempListObj=Temp.split("=");
                DateArry.put(TempListObj[0], TempListObj[1]);
            }else if(Temp.matches("(.+?)=")){
                String[] TempListObj=Temp.split("=");
                DateArry.put(TempListObj[0],"");
            }else{
                throw new BusinessException("参数无法分解！");
            }
        }
        return DateArry;
    }

    /**
     * Convert hex string to byte[]
     * @param hexString the hex string
     * @return byte[]
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    /**
     * Convert char to byte
     * @param c char
     * @return byte
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
    /**
     * 将map中的key和value转化为字符，并以index分开
     *
     * @param params
     * @return
     */
    public static String mapToStrByIndex(Map<String, Object> params, String index) {
        StringBuffer returnStr = new StringBuffer();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            returnStr.append(entry.getKey() + "=" + entry.getValue() + index);
        }
        return returnStr.substring(0, returnStr.length() - index.length());
    }

    /**
     * 将byte[] 转换成字符串
     *
     * @return
     */
    public static String byte2Hex(byte[] srcBytes) {
        StringBuilder hexRetSB = new StringBuilder();
        for (byte b : srcBytes) {
            String hexString = Integer.toHexString(0x00ff & b);
            hexRetSB.append(hexString.length() == 1 ? 0 : "").append(hexString);
        }
        return hexRetSB.toString();
    }

    /**
     * 将16进制字符串转为转换成字符串
     *
     * @param source
     * @return
     */
    public static byte[] hex2Bytes(String source) {
        byte[] sourceBytes = new byte[source.length() / 2];
        for (int i = 0; i < sourceBytes.length; i++) {
            sourceBytes[i] = (byte) Integer.parseInt(source.substring(i * 2, i * 2 + 2), 16);
        }
        return sourceBytes;
    }

    /**
     * 组装跳转url
     *
     * @param redirectUrl
     * @param redirectParams
     * @return
     */
    public static String getRedirectUrl(String redirectUrl, Map<String, String> redirectParams) {
        StringBuffer stringBuffer = new StringBuffer();
        for (Map.Entry<String, String> entry : redirectParams.entrySet()) {
            stringBuffer.append(entry.getKey() + "=" + Encodes.urlEncode(entry.getValue()) + "&");
        }
        return redirectUrl + "?" + stringBuffer.substring(0, stringBuffer.length() - 1);
    }

    /**
     * 异步通知请求参数转map
     * @return
     */
    public static Map<String, String> getNotifyParameters(ServletRequest request) {
        Map<String, String> params = new TreeMap<>();
        Enumeration<String> enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String[] values = request.getParameterValues(name);
            if (values == null || values.length == 0) {
                continue;
            }
            String value = values[0];
            // 注意：这里是判断不为null,没有包括空字符串的判断。
            if (value != null) {
                params.put(name, value);
            }
        }
        return params;
    }
}
